package lhz.ack;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import lhz.RabbitMqUtils;

import java.util.concurrent.TimeUnit;

/**
 * @Author: LiHuaZhi
 * @Date: 2021/10/20 20:30
 * @Description:
 **/
public class Consumer02 {
    /**
     * 设置队列名称
     */
    private final static String ACK_QUEUE_NAME = "ack_queue_name";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMqUtils.getChannel();

        System.out.println("C2 等待接收消息处理时间较短");

        //消息消费的时候如何处理消息
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {

            String message = new String(delivery.getBody());
            System.out.println("C2接收到消息:" + message);
            // 模拟处理时间
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 1.消息标记 tag
            // 2.是否批量应答未应答消息
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            System.out.println("C2消息处理完成，已确认");
        };

        //采用手动应答
        boolean autoAck = false;
        channel.basicConsume(ACK_QUEUE_NAME, autoAck, deliverCallback, (consumerTag) -> {
            System.out.println(consumerTag + "消费者取消消费接口回调逻辑");
        });
    }
}